package com.lntea.context;

import java.util.List;

import com.lntea.beans.BeanPostProcessor;
import com.lntea.factory.AbstractBeanFactory;

public abstract class AbstractApplicationContext implements ApplicationContext{
	private AbstractBeanFactory beanFactory;
	
	public AbstractApplicationContext(AbstractBeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}
	
	public void refresh() throws Exception{
		loadBeanDefinitions(beanFactory);
		registerBeanPostProcessors(beanFactory);
		onRefresh();
	}
	
	protected void registerBeanPostProcessors(AbstractBeanFactory beanFactory) throws Exception {
		List<BeanPostProcessor> beanPostProcessors = beanFactory.getBeansForType(BeanPostProcessor.class);
		for(BeanPostProcessor beanPostProcessor : beanPostProcessors){
			beanFactory.addBeanPostProcessor(beanPostProcessor);
		}
	}

	protected void onRefresh() throws Exception {
		beanFactory.preInstantiateSingletons();
	}

	protected abstract void loadBeanDefinitions(AbstractBeanFactory beanFactory) throws Exception;
	
	@Override
	public Object getBean(String beanName) throws Exception{
		return beanFactory.getBean(beanName);
	}
}
